const { accountModel } = require("../models/account")
const { userModel } = require("../models/user")
const { createToken } = require('../utils/auth')
const md5 = require('md5')

class TokenController {
  static async login(ctx) {
    // 参数校验
    ctx.verifyParams({
      name: { type: 'string', min: 1, max: 24, required: true },
      pass: { type: 'string', min: 6, max: 16, required: true },
    })

    // 获取参数
    const name = ctx.request.body.name
    const pass = md5(ctx.request.body.pass)

    // 业务逻辑/数据库操作
    // 登录验证
    let account = await accountModel.findOne({ name, pass })
    if (!account) {
      console.log("name:", name, " pass:", pass)
      ctx.err({ message: "用户名或密码错误" })
      return
    }
    // console.log("account:", account)

    // 获取用户信息
    let user = await userModel.findById(account._id)
    if (!user) {
      ctx.err({ message: "用户异常：用户不存在" })
      return
    }
    console.log("user:", user)

    // token
    const token = createToken({
      user
    })

    // 返回请求结果
    ctx.succ({
      data: {
        token
      }
    })
  }
}

module.exports = {
  TokenController
}